package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.entity.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 课程分类(CourseCategory)表服务实现类
 *
 * @author hanwangfei
 * @since 2023-03-14 13:20:31
 */
@Service("courseCategoryService")
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = getBaseMapper().selectTreeNodes(id);

        //找到每个节点的子节点，进行数据填充
        Map<String, CourseCategoryTreeDto> map = courseCategoryTreeDtos.stream().filter(item -> !id.equals(item.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));

        //定义一个List作为返回结果
        List<CourseCategoryTreeDto> categoryTreeDtoList= new ArrayList<>();
        courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).forEach(item -> {
            if(item.getParentid().equals(id)){
                categoryTreeDtoList.add(item);
            }
            //找到节点的父节点
            CourseCategoryTreeDto courseCategoryTreeDto = map.get(item.getParentid());
            if(courseCategoryTreeDto != null){
                if(courseCategoryTreeDto.getChildrenTreeNodes() == null){
                    //如果该父节点的ChildTreeNodes为空，需要new出来
                    courseCategoryTreeDto.setChildrenTreeNodes(new ArrayList<>());
                }
                //将当前节点塞到它的父节点属性中
                courseCategoryTreeDto.getChildrenTreeNodes().add(item);
            }
        });

        return categoryTreeDtoList;
    }
}
